﻿using System;
using System.Activities;
using VMware.Vim;

namespace VMWareActivities
{
    using Microsoft.TeamFoundation.Build.Client;

    [BuildActivity(HostEnvironmentOption.All)]
    public sealed class ConnectToVMWareServerActivity : CodeActivity
    {
        [RequiredArgument]
        public InArgument<string> ServerName { get; set; }

        [RequiredArgument]
        public InArgument<Nullable<CommunicationProtocol>> ServerCommunicationProtocol { get; set; }
        
        [RequiredArgument]
        public InArgument<ushort> ServerPort { get; set; }

        [RequiredArgument]
        public InArgument<string> UserName { get; set; }

        [RequiredArgument]
        public InArgument<string> Password { get; set; }

        [RequiredArgument]
        public OutArgument<VimClient> VMWareConnection { get; set; }

        /// <summary>
        /// When implemented in a derived class, performs the execution of the activity.
        /// </summary>
        /// <param name="context">The execution context under which the activity executes.</param>
        protected override void Execute(CodeActivityContext context)
        {
            string serverName = context.GetValue(this.ServerName);            
            CommunicationProtocol? serverCommunicationProtocol = context.GetValue(this.ServerCommunicationProtocol);
            ushort? serverPort = context.GetValue(this.ServerPort) != 0 ? ((ushort?)context.GetValue(this.ServerPort)) : null;
            string userName = context.GetValue(this.UserName);
            string password = context.GetValue(this.Password);
            
            VimClient client = ConnectToVMWareServer(serverName, serverCommunicationProtocol, serverPort, userName, password);
            context.SetValue(this.VMWareConnection, client);
        }

        /// <summary>
        /// Connects to VM ware server.
        /// </summary>
        /// <param name="serverName">Name of the server.</param>
        /// <param name="serverCommunicationProtocol">The server communication protocol.</param>
        /// <param name="serverPort">The server port.</param>
        /// <param name="userName">Name of the user.</param>
        /// <param name="password">The password.</param>
        /// <returns></returns>
        public static VimClient ConnectToVMWareServer(string serverName, CommunicationProtocol? serverCommunicationProtocol, ushort? serverPort, string userName, string password)
        {
            var client = new VimClient();
            client.Connect(serverName, serverCommunicationProtocol, serverPort);
            client.Login(userName, password);
            return client;
        }
    }
}
